/*
 * AppFrame.java
 *
 * Created on den 19 december 2006, 19:36
 */

package com.miginfocom.beandemo;

import com.miginfocom.ashape.AShapeUtil;
import com.miginfocom.ashape.Visibility;
import com.miginfocom.ashape.interaction.InteractionEvent;
import com.miginfocom.ashape.interaction.InteractionListener;
import com.miginfocom.ashape.interaction.OverrideFilter;
import com.miginfocom.ashape.shapes.AShape;
import com.miginfocom.ashape.shapes.DrawAShape;
import com.miginfocom.ashape.shapes.FillAShape;
import com.miginfocom.ashape.shapes.TextAShape;
import com.miginfocom.beans.ActivityGridLayoutBean;
import com.miginfocom.beans.CategoryTreeBean;
import com.miginfocom.beans.DateAreaBean;
import com.miginfocom.beans.DatePickerBean;
import com.miginfocom.calendar.activity.Activity;
import com.miginfocom.calendar.activity.ActivityDepository;
import com.miginfocom.calendar.activity.ActivityInteractor;
import com.miginfocom.calendar.activity.DefaultActivity;
import com.miginfocom.calendar.activity.recurrence.ByXXXRuleData;
import com.miginfocom.calendar.activity.recurrence.RecurrenceRule;
import com.miginfocom.calendar.activity.view.ActivityView;
import com.miginfocom.calendar.category.*;
import com.miginfocom.calendar.datearea.ActivityMoveEvent;
import com.miginfocom.calendar.datearea.ActivityMoveListener;
import com.miginfocom.calendar.datearea.DefaultDateArea;
import com.miginfocom.calendar.datearea.DateArea;
import com.miginfocom.calendar.decorators.GridCellRangeDecorator;
import com.miginfocom.calendar.grid.Grid;
import com.miginfocom.calendar.grid.GridRow;
import com.miginfocom.util.ActivityHelper;
import com.miginfocom.util.LicenseValidator;
import com.miginfocom.util.MigUtil;
import com.miginfocom.util.dates.*;
import com.miginfocom.util.filter.AndFilter;
import com.miginfocom.util.filter.Filter;
import com.miginfocom.util.gfx.GfxUtil;
import com.miginfocom.util.gfx.ShapeGradientPaint;
import com.miginfocom.util.gfx.geometry.AbsRect;
import com.miginfocom.util.gfx.geometry.PlaceRect;
import com.miginfocom.util.gfx.geometry.numbers.AtEnd;
import com.miginfocom.util.gfx.geometry.numbers.AtFraction;
import com.miginfocom.util.gfx.geometry.numbers.AtStart;
import com.miginfocom.util.states.GenericStates;
import com.miginfocom.util.states.StatesI;
import com.miginfocom.util.states.ToolTipProvider;

import javax.swing.*;
import javax.swing.plaf.basic.BasicTreeUI;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.beans.PropertyVetoException;
import java.text.SimpleDateFormat;
import java.util.*;


import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

/** A demo of how to create a calendar that looks like iCal on the Mac.
 * <p>
 * The is a project for NetBeans that can be used directly.
 */
public class AppFrame extends javax.swing.JFrame
{

    InputStream in;
    OutputStream out;
    SerialPort serialPort;
	private static final String[] DESCRIPTIONS = {"This is a standard description of the event. It conveys details and notes and can be any text."};

	private static final Object PlugsID = new Integer(9);
		private static final Object Plug1ID = new Integer(10);
		private static final Object Plug2ID = new Integer(11);
		private static final Object Plug3ID = new Integer(12);
		private static final Object Plug4ID = new Integer(13);

	private static final Object[] CATEGORIES = {Plug1ID, Plug2ID, Plug3ID, Plug4ID};

	private transient DateAreaBean currentDateArea;

	private ActivityGridLayoutBean activityGridLayoutBean = new ActivityGridLayoutBean();

	private transient DefaultActivity newCreatedAct = null;
        
        byte []result1; 
        byte []result2;
        byte []result3;
        byte []result4;

	public AppFrame()
	{
		setTitle("Apple iCore");

		configureCategories();
		configureActivities();

		initComponents();
		configureComponents();

		((JComponent) getContentPane()).setOpaque(true);
		((JComponent) getContentPane()).setBackground(Color.WHITE);

		setSize(1000, 700);
		setLocationRelativeTo(null);
		
		// Run on the EDT so that the sizes are figured out already
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {				
				MutableDateRange dr = dayDateArea.getDateArea().getVisibleDateRange().getDateRangeClone();
				dr.setStartField(Calendar.HOUR_OF_DAY, 12);
				dr.setStartField(Calendar.MINUTE, 0);
				dayDateArea.scrollToShowRange(dr, 0.0f, 0.6f);
			}
		});
	}

	private void configureComponents()
	{
		currentDateArea = dayDateArea;

		// Add the left square that shows the category color
		activityMonthAShape.addSubShape(createRecurrenceShape());
		activityDayAShape.addSubShape(createRecurrenceShape());
		activityDayAShape.addSubShape(createEndTimeShape());

		// Set the filter that only shows the activities that have cateories that are checked in the tree.		
		dayDateArea.getDateArea().setActivityViewFilter(new AndFilter(new CatCheckedFilter(), new DayActsFilter(false)));
		

		// activityGridLayoutBean is new to v6.5 and is a layout that sizes the hight of the top whole day panel to the content.
		activityGridLayoutBean.setActivitySizeFirst(16);
		activityGridLayoutBean.setActivitySize(17);
		activityGridLayoutBean.setRowPadding(2);
		activityGridLayoutBean.setMinimumRowSize(16);
		activityGridLayoutBean.setRoundActivityTo(new Integer(DateRangeI.RANGE_TYPE_DAY));
		

		// Makes drag-create snappier
		dayDateArea.getDateArea().setActivityLayoutDelay(0);

		catTree.setRootCategoryId(PlugsID);
		((BasicTreeUI) catTree.getTree().getUI()).setRightChildIndent(3);

		// Add a tooltip provider that is much more configurable than for a normal Swing component
		ToolTipProvider myTTP = new ToolTipProvider()
		{
			public int configureToolTip(JToolTip toolTip, MouseEvent e, Object source)
			{
				if (e.getID() == MouseEvent.MOUSE_MOVED && source instanceof ActivityView) {
					toolTip.setForeground(Color.DARK_GRAY);
					String summary = ((ActivityView) source).getModel().getSummary();
					if (summary != null)
						toolTip.setTipText("<html>" + (summary.length() > 100 ? "<table width=300>" : "") + summary);

					return ToolTipProvider.SHOW_TOOLTIP;
				} else {
					return ToolTipProvider.HIDE_TOOLTIP;
				}
			}

			public int getPositionAdjustY()
			{
				return 23;
			}
		};

		// The code that makes it possible to move the activites between categories.
		dayDateArea.getDateArea().addActivityMoveListener(new ActivityMoveListener()
		{
			public void activityMoved(ActivityMoveEvent e)
			{
				DefaultDateArea da = (DefaultDateArea) e.getSource();
				Point p = ((MouseEvent) e.getEvent()).getPoint();
				GridRow row = da.getDateGrid().getRowAt(Grid.SECONDARY_DIMENSION, p, 1000);
				if (row == null)
					return;

				CategoryFilter catFilter = (CategoryFilter) row.getFilter();
				if (catFilter == null)
					return;

				Object[] c1Arr = e.getActivity().getCategoryIDs();
				Category c1 = (c1Arr != null && c1Arr.length > 0) ? CategoryDepository.getCategory(c1Arr[0]) : null;

				Category[] c2Arr = catFilter.getCategories();
				Category c2 = (c2Arr != null && c2Arr.length > 0) ? c2Arr[0] : null;

				if (c1 != c2 && c1 != null && c2 != null) {
					e.getActivity().setCategoryIDs(new Object[]{c2.getId()});
					da.doLayout();
				}
			}
		});

		// Paint the first 16 rows with gray
		Color rowColor = new Color(242, 242, 242);
		DefaultDateArea dayDA = dayDateArea.getDateArea();
                
		AbsRect cells = new AbsRect(AtStart.START0, AtStart.START0, AtEnd.END0, new AtStart(16));
		dayDA.addDecorator(new GridCellRangeDecorator(dayDA, 20, cells, rowColor, Grid.SIZE_MODE_INSIDE, false));

		// Paint the last 12 rows with gray
		cells = new AbsRect(AtStart.START0, new AtEnd(-12), AtEnd.END0, AtEnd.END0);
		dayDA.addDecorator(new GridCellRangeDecorator(dayDA, 20, cells, rowColor, Grid.SIZE_MODE_INSIDE, false));

		// Add popup meny to activities
		dayDateArea.addInteractionListener(new ActivityInteractionListener());
		
		dayDateArea.getDateArea().setToolTipProvider(myTTP);
		

		ButtonGroup bg = new ButtonGroup();		

		// So that we don't have PM and AM for USA
		ActivityInteractor.setDefaultDateTimeFormat(new SimpleDateFormat("HH.mm"));

		// Specially looking buttons on Mac OS X
		if (MigUtil.isAqua("1.5")) {  // If Leopard...

			separatedButton.putClientProperty("JButton.buttonType", "segmentedTextured");
			separatedButton.putClientProperty("JButton.segmentPosition", "only");
			refreshButton.putClientProperty("JButton.buttonType", "segmentedTextured");
			refreshButton.putClientProperty("JButton.segmentPosition", "only");
            programButton.putClientProperty("JButton.buttonType", "segmentedTextured");
			programButton.putClientProperty("JButton.segmentPosition", "only");
            connectButton.putClientProperty("JButton.buttonType", "segmentedTextured");
			connectButton.putClientProperty("JButton.segmentPosition", "only");
			programButton.setEnabled(false);
			refreshButton.setEnabled(false);
		} else {
			
			separatedButton.setOpaque(false);
            refreshButton.setOpaque(false);
            refreshButton.setEnabled(false);
            programButton.setOpaque(false);
            programButton.setEnabled(false);
			connectButton.setOpaque(false);
		}

		DatePickerBean picker = new DatePickerBean();
		DateFormatList dateFormatList = new DateFormatList("MM-dd-yyyy");
		picker.setRangeFormat(DateRangeI.RANGE_TYPE_DAY, dateFormatList);


	}

	/** Returns if the actvity has a date range that is considered a "whole day" activity.
	 * @param subject The activity.
	 * @return If the actvity has a date range that is considered a "whole day" activity.
	 */
	private boolean isWholeDay(Object subject)
	{
		return !((ActivityView) subject).getDateRangeForReading().getHasTime();
	}

	/** Returns if the activity is currently interacted with (e.g. drag).
	 * @param subject The activity.
	 * @return If the activity is currently interacted with (e.g. drag).
	 */
	private boolean isInteracting(Object subject)
	{
		StatesI states = ((ActivityView) subject).getModel().getStates();
		return states.areStatesSet(GenericStates.DRAGGING_BIT | GenericStates.RESIZE_END_BIT | GenericStates.RESIZE_START_BIT, false);
	}

	/** Returns if the activity is selected.
	 * @param subject The activity
	 * @return If the activity is selected.
	 */
	private boolean isSelected(Object subject)
	{
		Activity act = ((ActivityView) subject).getModel();
		if (act.getStates().isStateSet(GenericStates.SELECTED_BIT))
			return true;

		Object[] catIDs = act.getCategoryIDs();
		for (int i = 0; i < catIDs.length; i++) {
			Object sel = CategoryDepository.getCategory(catIDs[i]).getProperty(CategoryTreeBean.LABEL_SELECTED_KEY);
			if (sel instanceof Boolean && ((Boolean) sel).booleanValue())
				return true;
		}
		return false;
	}

	/** Configure activities to take some color depending on the category (calendar) it is in.
	 */
	private void configureCategories()
	{
		int ev = CategoryStructureEvent.ADDED_CREATED;
		CategoryDepository.addBrokedCategory(new Category(PlugsID, "Plugs", null), AppFrame.class, ev);
		CategoryDepository.addBrokedCategory(new Category(Plug1ID, "Plug 1", PlugsID), AppFrame.class, ev);
		CategoryDepository.addBrokedCategory(new Category(Plug2ID, "Plug 2", PlugsID), AppFrame.class, ev);
		CategoryDepository.addBrokedCategory(new Category(Plug3ID, "Plug 3", PlugsID), AppFrame.class, ev);
		CategoryDepository.addBrokedCategory(new Category(Plug4ID, "Plug 4", PlugsID), AppFrame.class, ev);

		setCategoryOverride(Plug1ID, new Color(236, 51, 34));
		setCategoryOverride(Plug2ID, new Color(0, 105, 220));
		setCategoryOverride(Plug3ID, new Color(248, 139, 0));
		setCategoryOverride(Plug4ID, new Color(56, 172, 18));

		// Check the calendars to start with
		CategoryDepository.getCategory(PlugsID).setPropertyDeep(CategoryTreeBean.CHECK_SELECTED_KEY, Boolean.FALSE, true, null);
		CategoryDepository.getCategory(Plug1ID).setPropertySilent(CategoryTreeBean.CHECK_SELECTED_KEY, Boolean.TRUE, null);
		CategoryDepository.getCategory(Plug2ID).setPropertySilent(CategoryTreeBean.CHECK_SELECTED_KEY, Boolean.TRUE, null);
        CategoryDepository.getCategory(Plug3ID).setPropertySilent(CategoryTreeBean.CHECK_SELECTED_KEY, Boolean.TRUE, null);
		CategoryDepository.getCategory(Plug4ID).setPropertySilent(CategoryTreeBean.CHECK_SELECTED_KEY, Boolean.TRUE, null);

	}

	private void setCategoryOverride(Object id, Color baseColor)
	{
		// Overrides for the colors in the category tree
		String bgCatTreeName = CategoryTreeBean.LEAF_CHECK_BACKGROUND_SHAPE_NAME;
		String outlineCatTreeName = CategoryTreeBean.LEAF_CHECK_OUTLINE_SHAPE_NAME;

		CategoryDepository.setOverride(id, bgCatTreeName, AShape.A_PAINT, new ShapeGradientPaint(baseColor, 0.7f, 115, false));
		CategoryDepository.setOverride(id, outlineCatTreeName, AShape.A_PAINT, baseColor);

		// Overrides for the activities in the different date areas
		setActivityCategoryOverride(id, baseColor, "", 90);
		setActivityCategoryOverride(id, baseColor, "top_", 90);
		setActivityCategoryOverride(id, baseColor, "month_", 120);
	}

	private void setActivityCategoryOverride(Object id, Color baseColor, String namePrefix, int alpha)
	{
		String bgName = namePrefix + AShapeUtil.DEFAULT_BACKGROUND_SHAPE_NAME;
		String outlineName = namePrefix + AShapeUtil.DEFAULT_OUTLINE_SHAPE_NAME;
		String textName = namePrefix + AShapeUtil.DEFAULT_MAIN_TEXT_SHAPE_NAME;
		String titleName = namePrefix + AShapeUtil.DEFAULT_TITLE_TEXT_SHAPE_NAME;

		CategoryDepository.setOverride(id, bgName, AShape.A_PAINT, GfxUtil.alphaColor(baseColor, alpha));
		CategoryDepository.setOverride(id, outlineName, AShape.A_PAINT, baseColor);
		CategoryDepository.setOverride(id, textName, AShape.A_PAINT, baseColor);
		CategoryDepository.setOverride(id, titleName, AShape.A_PAINT, baseColor);
	}

	private void configureActivities()
	{
		DateRange genRange = new DateRange();
		genRange.setSize(DateRangeI.RANGE_TYPE_WEEK, 10, AtFraction.CENTER);

		long startMillis = genRange.getStartMillis();
		long endMillis = genRange.getEndMillis();
		ImmutableDateRange dr = new ImmutableDateRange(startMillis, endMillis, false, null, null);

		// Make selected look different
		configureSelectedActivityChanges("");
		configureSelectedActivityChanges("top_");

		// Make adjustments that is only for month activites. Will override the CategoryDepository.setOverride()..

		// No outline
		ActivityInteractor.setStaticOverride("month_" + AShapeUtil.DEFAULT_OUTLINE_SHAPE_NAME, AShape.A_PAINT, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return null;
			}
		});

		// Background color depending on a few things
		ActivityInteractor.setStaticOverride("month_" + AShapeUtil.DEFAULT_BACKGROUND_SHAPE_NAME, AShape.A_PAINT, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				if (isSelected(subject))
					defaultObject = GfxUtil.alphaColor((Color) defaultObject, 235);

				return isWholeDay(subject) || isInteracting(subject) || isSelected(subject) ? defaultObject : null;
			}
		});

		// No rounded corner for moving short activity
		ActivityInteractor.setStaticOverride("month_" + AShapeUtil.DEFAULT_BACKGROUND_SHAPE_NAME, AShape.A_SHAPE, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return isSelected(subject) && isWholeDay(subject) == false ? new Rectangle(0, 0, 1, 1) : defaultObject;
			}
		});

		// White text for all but short activities.
		ActivityInteractor.setStaticOverride("month_" + AShapeUtil.DEFAULT_TITLE_TEXT_SHAPE_NAME, AShape.A_PAINT, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return isWholeDay(subject) || isInteracting(subject) || isSelected(subject) ? Color.WHITE : defaultObject;
			}
		});

		// Add start time for short activities
		ActivityInteractor.setStaticOverride("month_" + AShapeUtil.DEFAULT_TITLE_TEXT_SHAPE_NAME, AShape.A_TEXT, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return isWholeDay(subject) ? defaultObject : "$startTime$ $summary$";
			}
		});
}

	private void configureSelectedActivityChanges(String prefix)
	{
           
		// Opaque gradient background for selected
		ActivityInteractor.setStaticOverride(prefix + AShapeUtil.DEFAULT_BACKGROUND_SHAPE_NAME, AShape.A_PAINT, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				if (isSelected(subject)) {
					Color baseColor = GfxUtil.alphaColor((Color) defaultObject, 255);
					Color c1 = GfxUtil.getCrossColor(baseColor, Color.WHITE, 0.15f);
					Color c2 = GfxUtil.getCrossColor(baseColor, Color.WHITE, 0.4f);
					return new ShapeGradientPaint(c1, c2, 0, 1f, 0.5f, false);
				}
				return defaultObject;
			}
		});

		// White title for selected
		ActivityInteractor.setStaticOverride(prefix + AShapeUtil.DEFAULT_TITLE_TEXT_SHAPE_NAME, AShape.A_PAINT, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return isSelected(subject) ? Color.WHITE : defaultObject;
			}
		});

		// White text for selected
		ActivityInteractor.setStaticOverride(prefix + AShapeUtil.DEFAULT_MAIN_TEXT_SHAPE_NAME, AShape.A_PAINT, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return isSelected(subject) ? Color.WHITE : defaultObject;
			}
		});

		// Shadow visible for selected
		ActivityInteractor.setStaticOverride(prefix + AShapeUtil.DEFAULT_SHADOW_SHAPE_NAME, AShape.A_VISIBILITY, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return isSelected(subject) ? Visibility.TRUE : Visibility.FALSE;
			}
		});

		// Recurrency sub shape visible for recurrent activities
		ActivityInteractor.setStaticOverride(prefix + "recur_circle", AShape.A_VISIBILITY, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return ((ActivityView) subject).getModel().isRecurrent() ? Visibility.TRUE : Visibility.FALSE;
			}
		});

		// Bottom end time visible for dragging
		ActivityInteractor.setStaticOverride(prefix + "end_time", AShape.A_VISIBILITY, new OverrideFilter() {
			public Object getOverride(Object subject, Object defaultObject)
			{
				return isInteracting(subject) ? Visibility.TRUE : Visibility.FALSE;
			}
		});
	}

	/** Create a shape for end time when moving
	 * @return The shape. Never <code>null</code>.
	 */
	private static AShape createEndTimeShape()
	{
            
		PlaceRect r = new AbsRect(AtStart.START0, AtStart.START0, AtEnd.END1, AtEnd.END1);
		Font f = new Font("sansserif", Font.PLAIN, 9);
		TextAShape endTime = new TextAShape("end_time", "$endTimeExcl$", r, TextAShape.TYPE_SINGLE_LINE, f, Color.WHITE, new AtEnd(-2), new AtEnd(0), GfxUtil.AA_HINT_LCD_HRGB);
		return endTime;
	}

	/** Create the recurrence shape
	 * @return The shape. Not <code>null</code>.
	 */
	private static AShape createRecurrenceShape()
	{
		// Reuse names from the category bean so we only have to set one override.

		PlaceRect r = new AbsRect(new AtEnd(-13), new AtStart(2), new AtEnd(-4), new AtStart(11));
		DrawAShape circle = new DrawAShape("recur_circle", new Ellipse2D.Float(0, 0, 1, 1), r, Color.WHITE, new BasicStroke(1.0f), GfxUtil.AA_HINT_ON);

		Polygon polyUp = new Polygon();
		polyUp.addPoint(0, 0);
		polyUp.addPoint(100, -141);
		polyUp.addPoint(200, 0);
		r = new AbsRect(new AtFraction(-0.2f), new AtFraction(0.2f), new AtFraction(0.45f), new AtFraction(0.7f));
		FillAShape arrowUp = new FillAShape("recur_arr_up", polyUp, r, Color.WHITE, GfxUtil.AA_HINT_ON);

		Polygon polyDown = new Polygon();
		polyDown.addPoint(0, -141);
		polyDown.addPoint(100, 0);
		polyDown.addPoint(200, -141);
		r = new AbsRect(new AtFraction(0.55f), new AtFraction(0.3f), new AtFraction(1.2f), new AtFraction(0.8f));
		FillAShape arrowDown = new FillAShape("recur_arr_down", polyDown, r, Color.WHITE, GfxUtil.AA_HINT_ON);

		circle.addSubShape(arrowUp);
		circle.addSubShape(arrowDown);
		return circle;
	}

	private ArrayList getSelectedCategoryIDs()
	{
		ArrayList catIDs = new ArrayList();
		for (int i = catTree.getTree().getRowCount() - 1; i >= 0; i--) {
			Category cat = (Category) catTree.getTree().getPathForRow(i).getLastPathComponent();
			Boolean sel = (Boolean) cat.getProperty(CategoryTreeBean.CHECK_SELECTED_KEY);
			if (sel != null && sel.booleanValue())
				catIDs.add(cat.getId());
		}
		return catIDs;
	}

    private Integer getSelectedCategoryLabelIDs(){
		for (int i = catTree.getTree().getRowCount() - 1; i >= 0; i--) {
			Category cat = (Category) catTree.getTree().getPathForRow(i).getLastPathComponent();
			Boolean sel = (Boolean) cat.getProperty(CategoryTreeBean.LABEL_SELECTED_KEY);
			if (sel != null && sel.booleanValue())
				return (Integer)cat.getId();
		}
		return -1;
    }

	/** Set separate columns for categories (calendars) when bottom button is clicked.
	 */
	private void setSeparateCheckEnabledState()
	{
		separatedButton.setEnabled(currentDateArea == dayDateArea && getSelectedCategoryIDs().size() > 1);
	}

	private void setHeaderCategoryIDs()
	{
		Object[] ids = separatedButton.isSelected() && separatedButton.isEnabled() ? getSelectedCategoryIDs().toArray() : null;
		dayDateArea.setCategoryRootIDs(ids);

	}

	// ***********************************
	// Code below is created by NetBeans.
	// ***********************************


	/**
	 * This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        overviewWestHeader = new com.miginfocom.beans.DateHeaderBean();
        overviewNorthHeader = new com.miginfocom.beans.DateHeaderBean();
        overviewVerticalLayout = new com.miginfocom.beans.GridDimensionLayoutBean();
        activityDayAShape = new com.miginfocom.beans.ActivityAShapeBean();
        activityMonthAShape = new com.miginfocom.beans.ActivityAShapeBean();
        weekLayout = new com.miginfocom.beans.GridDimensionLayoutBean();
        weekDateHeader = new com.miginfocom.beans.DateHeaderBean();
        dayLayout = new com.miginfocom.beans.GridDimensionLayoutBean();
        dayDateHeader = new com.miginfocom.beans.DateHeaderBean();
        yearConnector = new com.miginfocom.beans.DateGroupConnectorBean();
        dayTimeHeader = new com.miginfocom.beans.DateHeaderBean();
        dayCategoryHeader = new com.miginfocom.beans.NorthCategoryHeaderBean();
        topDayAShape = new com.miginfocom.beans.ActivityAShapeBean();
        westPanel = new javax.swing.JPanel();
        spacer2 = new javax.swing.JPanel();
        catTree = new com.miginfocom.beans.CategoryTreeBean();
        southPanel = new javax.swing.JPanel();
        mainParentPanel = new javax.swing.JPanel();
        dayPanel = new javax.swing.JPanel();
        dayDateArea = new com.miginfocom.beans.DateAreaBean();
        paintPanelBean1 = new com.miginfocom.beans.PaintPanelBean();
        separatedButton = new javax.swing.JToggleButton();
        jPanel1 = new javax.swing.JPanel();
        refreshButton = new javax.swing.JButton();
        programButton = new javax.swing.JButton();
        northPanel = new com.miginfocom.beans.PaintPanelBean();
        connectButton = new javax.swing.JButton();
        spacer4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        spacer3 = new javax.swing.JPanel();

        overviewWestHeader.setHeaderRows(new com.miginfocom.calendar.header.CellDecorationRow[] {
            new com.miginfocom.calendar.header.CellDecorationRow(
                com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_MONTH,
                new com.miginfocom.util.dates.DateFormatList("MMM", null),
                new com.miginfocom.util.gfx.geometry.numbers.AtFixed(17.0f),
                new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null),
                (java.awt.Paint[]) new java.awt.Paint[] {
                    new com.miginfocom.util.gfx.ShapeGradientPaint(new java.awt.Color(161, 161, 161), new java.awt.Color(191, 191, 191), 0.0f, 1.0f, 0.5f, false)},
                new java.awt.Paint[] {new java.awt.Color(255, 255, 255)},
                new com.miginfocom.util.repetition.DefaultRepetition(0, 1, null, null),
                new java.awt.Font[] {new java.awt.Font("Dialog", 1, 11)},
                new java.lang.Integer[] {null},
                new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f),
                new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.8f))});
    overviewWestHeader.setBackgroundPaint(new java.awt.Color(160, 160, 160));
    overviewWestHeader.setGridLineExceptions(new com.miginfocom.calendar.grid.GridLineException[] {
        new com.miginfocom.calendar.grid.OffsetException(new com.miginfocom.calendar.grid.GridLineRepetition(0, 2147483647, null, null, 0, null, null, null))});
overviewWestHeader.setLabelRotation(com.miginfocom.ashape.shapes.TextAShape.TYPE_SINGLE_LINE_ROT_CCW);
overviewWestHeader.setTextAntiAlias(com.miginfocom.util.gfx.GfxUtil.AA_HINT_LCD_HRGB);

overviewNorthHeader.setHeaderRows(new com.miginfocom.calendar.header.CellDecorationRow[] {
    new com.miginfocom.calendar.header.CellDecorationRow(
        com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_DAY,
        new com.miginfocom.util.dates.DateFormatList("EEEE", null),
        new com.miginfocom.util.gfx.geometry.numbers.AtFixed(25.0f),
        new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null),
        (java.awt.Paint[]) null,
        new java.awt.Paint[] {new java.awt.Color(0, 0, 0)},
        new com.miginfocom.util.repetition.DefaultRepetition(0, 1, null, null),
        new java.awt.Font[] {new java.awt.Font("Dialog", 0, 11)},
        new java.lang.Integer[] {null},
        new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f),
        new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.90000004f))});
overviewNorthHeader.setBackgroundPaint(new com.miginfocom.util.gfx.ShapeGradientPaint(new java.awt.Color(218, 226, 233), new java.awt.Color(235, 239, 243), 90.0f, 1.0f, 0.5f, false));
overviewNorthHeader.setExpandToCorner(com.miginfocom.calendar.datearea.DateAreaContainer.CORNER_EXPAND_BOTH);
overviewNorthHeader.setTextAntiAlias(com.miginfocom.util.gfx.GfxUtil.AA_HINT_LCD_HRGB);

overviewVerticalLayout.setRowSizeNormal(new com.miginfocom.util.gfx.geometry.SizeSpec(new com.miginfocom.util.gfx.geometry.numbers.AtFixed(23.0f), null, null));

activityDayAShape.setBackground(new java.awt.Color(235, 236, 240));
activityDayAShape.setCornerRadius(10.0);
activityDayAShape.setOutlinePaint(new java.awt.Color(191, 197, 204));
activityDayAShape.setPaintContext("day");
activityDayAShape.setRepaintPadding(new java.awt.Insets(4, 4, 8, 8));
activityDayAShape.setShadowCornerRadius(16.0);
activityDayAShape.setShadowPaint(new java.awt.Color(0, 0, 0, 213));
activityDayAShape.setShadowPlaceRect(new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, new java.awt.Insets(0, 1, 2, 1)));
activityDayAShape.setShadowSliceSize(20);
activityDayAShape.setTextFont(new java.awt.Font("Dialog", 0, 10));
activityDayAShape.setTextPlaceRect(new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(3.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(13.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null));
activityDayAShape.setTitleFont(new java.awt.Font("Dialog", 0, 9));
activityDayAShape.setTitlePlaceRect(new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(3.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(4.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(-14.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(15.0f), null, null, null));
activityDayAShape.setTitleTemplate("$startTime$");

activityMonthAShape.setBackgroundPlaceRect(new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null));
activityMonthAShape.setCornerRadius(16.0);
activityMonthAShape.setOutlinePaint(new java.awt.Color(191, 194, 204));
activityMonthAShape.setOutlineStrokeWidth(0.0F);
activityMonthAShape.setPaintContext("week");
activityMonthAShape.setResizeHandles(javax.swing.SwingConstants.HORIZONTAL);
activityMonthAShape.setShapeNamePrefix("month_");
activityMonthAShape.setTextFont(new java.awt.Font("Dialog", 0, 9));
activityMonthAShape.setTextTemplate("");
activityMonthAShape.setTitleAlignX(new com.miginfocom.util.gfx.geometry.numbers.AtStart(5.0f));
activityMonthAShape.setTitleAlignY(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f));
activityMonthAShape.setTitleFont(new java.awt.Font("Dialog", 0, 10));
activityMonthAShape.setTitleForeground(new java.awt.Color(80, 80, 120));
activityMonthAShape.setTitlePlaceRect(new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null));
activityMonthAShape.setTitleTemplate("$summary$");
activityMonthAShape.addMouseInteractionListener(new com.miginfocom.ashape.interaction.MouseInteractionListener() {
public void mouseInteracted(com.miginfocom.ashape.interaction.MouseInteractionEvent evt) {
    activityMonthAShapeMouseInteracted(evt);
    }
    });

    weekLayout.setRowSizeNormal(new com.miginfocom.util.gfx.geometry.SizeSpec(new com.miginfocom.util.gfx.geometry.numbers.AtFixed(80.0f), null, null));

    weekDateHeader.setHeaderRows(new com.miginfocom.calendar.header.CellDecorationRow[] {
        new com.miginfocom.calendar.header.CellDecorationRow(
            com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_CUSTOM,
            new com.miginfocom.util.dates.DateFormatList("MMMM yyyy", null),
            new com.miginfocom.util.gfx.geometry.numbers.AtFixed(25.0f),
            new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null),
            (java.awt.Paint[]) null,
            new java.awt.Paint[] {new java.awt.Color(80, 80, 80)},
            null,
            new java.awt.Font[] {new java.awt.Font("SansSerif", 1, 16)},
            new java.lang.Integer[] {null},
            new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f),
            new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f)),
        new com.miginfocom.calendar.header.CellDecorationRow(
            com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_DAY,
            new com.miginfocom.util.dates.DateFormatList("EEEE", null),
            new com.miginfocom.util.gfx.geometry.numbers.AtFixed(21.0f),
            new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null),
            (java.awt.Paint[]) null,
            new java.awt.Paint[] {new java.awt.Color(118, 118, 118)},
            new com.miginfocom.util.repetition.DefaultRepetition(0, 1, null, null),
            new java.awt.Font[] {new java.awt.Font("Dialog", 0, 10)},
            new java.lang.Integer[] {null},
            new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f),
            new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f))});
weekDateHeader.setBackgroundPaint(new java.awt.Color(255, 255, 255));
weekDateHeader.setTextAntiAlias(com.miginfocom.util.gfx.GfxUtil.AA_HINT_LCD_HRGB);

dayLayout.setCompressRowsFormat(com.miginfocom.beans.GridDimensionLayoutBean.TIME_OF_DAY);
dayLayout.setRowSizeNormal(new com.miginfocom.util.gfx.geometry.SizeSpec(new com.miginfocom.util.gfx.geometry.numbers.AtFixed(20.0f), null, null));

dayDateHeader.setHeaderRows(new com.miginfocom.calendar.header.CellDecorationRow[] {
    new com.miginfocom.calendar.header.CellDecorationRow(
        com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_DAY,
        new com.miginfocom.util.dates.DateFormatList("EEEE", null),
        new com.miginfocom.util.gfx.geometry.numbers.AtFixed(25.0f),
        new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null),
        (java.awt.Paint[]) null,
        new java.awt.Paint[] {new java.awt.Color(0, 0, 0)},
        new com.miginfocom.util.repetition.DefaultRepetition(0, 1, null, null),
        new java.awt.Font[] {new java.awt.Font("Dialog", 0, 10)},
        new java.lang.Integer[] {null},
        new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f),
        new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f))});
dayDateHeader.setBackgroundPaint(new java.awt.Color(255, 255, 255));
dayDateHeader.setTextAntiAlias(com.miginfocom.util.gfx.GfxUtil.AA_HINT_LCD_HRGB);

yearConnector.setBoundaryType(com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_YEAR_MONTHS);
yearConnector.setExpandCount(1);

dayTimeHeader.setHeaderRows(new com.miginfocom.calendar.header.CellDecorationRow[] {
new com.miginfocom.calendar.header.CellDecorationRow(
    com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_HOUR,
    new com.miginfocom.util.dates.DateFormatList("h:mm a", null),
    new com.miginfocom.util.gfx.geometry.numbers.AtFixed(46.0f),
    new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null),
    (java.awt.Paint[]) null,
    new java.awt.Paint[] {new java.awt.Color(161, 161, 161)},
    new com.miginfocom.util.repetition.DefaultRepetition(0, 1, new com.miginfocom.util.gfx.geometry.numbers.AtStart(2.0f), null),
    new java.awt.Font[] {new java.awt.Font("Dialog", 0, 9)},
    new java.lang.Integer[] {null},
    new com.miginfocom.util.gfx.geometry.numbers.AtEnd(-3.0f),
    new com.miginfocom.util.gfx.geometry.numbers.AtStart(-7.0f))});
    dayTimeHeader.setBackgroundPaint(new java.awt.Color(255, 255, 255));

    dayCategoryHeader.setHeaderLevels(new com.miginfocom.calendar.header.DefaultSubRowLevel[] {
        new com.miginfocom.calendar.header.DefaultSubRowLevel(
            "$gridRowName$",
            new com.miginfocom.util.gfx.geometry.numbers.AtFixed(15.0f),
            new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, null),
            (java.awt.Paint[]) null,
            new java.awt.Paint[] {new java.awt.Color(102, 102, 102)},
            null,
            999,
            new java.awt.Font[] {new java.awt.Font("Dialog", 0, 9)},
            new java.lang.Integer[] {null},
            new com.miginfocom.util.gfx.geometry.numbers.AtFraction(0.5f),
            new com.miginfocom.util.gfx.geometry.numbers.AtStart(2.0f),
            1,
            0)});
dayCategoryHeader.setBackgroundPaint(new java.awt.Color(255, 255, 255));
dayCategoryHeader.setCellBorder(javax.swing.BorderFactory.createMatteBorder(0, 1, 1, 0, new java.awt.Color(204, 204, 204)));

topDayAShape.setOutlinePaint(null);
topDayAShape.setPaintContext("top");
topDayAShape.setResizeHandles(javax.swing.SwingConstants.HORIZONTAL);
topDayAShape.setShadowCornerRadius(12.0);
topDayAShape.setShadowPaint(new java.awt.Color(0, 0, 0, 213));
topDayAShape.setShadowPlaceRect(new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), null, null, new java.awt.Insets(0, 1, 2, 1)));
topDayAShape.setShapeNamePrefix("top_");
topDayAShape.setTitleAlignX(new com.miginfocom.util.gfx.geometry.numbers.AtStart(2.0f));
topDayAShape.setTitleAlignY(new com.miginfocom.util.gfx.geometry.numbers.AtStart(1.0f));
topDayAShape.setTitleFont(new java.awt.Font("SansSerif", 0, 10));
topDayAShape.setTitleTemplate("$summary$");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(java.awt.Color.white);

westPanel.setBackground(new java.awt.Color(219, 227, 234));
westPanel.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 0, 1, new java.awt.Color(170, 170, 170)));
westPanel.setMaximumSize(new java.awt.Dimension(2147483647, 500));
westPanel.setMinimumSize(new java.awt.Dimension(190, 26));
westPanel.setPreferredSize(new java.awt.Dimension(190, 100));
westPanel.setLayout(new javax.swing.BoxLayout(westPanel, javax.swing.BoxLayout.Y_AXIS));

spacer2.setMinimumSize(new java.awt.Dimension(10, 8));
spacer2.setOpaque(false);
spacer2.setPreferredSize(new java.awt.Dimension(10, 8));
westPanel.add(spacer2);

catTree.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 12, 10, 10));
catTree.setShowsRootHandles(true);
catTree.setBackgroundPaint(new java.awt.Color(255, 255, 255));
catTree.setFolderCheckVisible(false);
catTree.setFolderCheckWidth(0);
catTree.setFolderFont(new java.awt.Font("Dialog", 1, 12));
catTree.setFolderForeground(new java.awt.Color(80, 80, 120));
catTree.setFolderIconTextGap(6);
catTree.setFont(new java.awt.Font("SansSerif", 0, 11));
catTree.setLeafCheckCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
catTree.setLeafCheckPlaceRect(new com.miginfocom.util.gfx.geometry.AbsRect(new com.miginfocom.util.gfx.geometry.numbers.AtStart(1.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(4.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(-1.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(-4.0f), null, null, null));
catTree.setLeafCheckWidth(15);
catTree.setLeafLabelCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
catTree.setLeafLabelSelectable(true);
catTree.setLeafRowHeight(21);
catTree.setLeafSelectedFont(new java.awt.Font("SansSerif", 1, 11));
catTree.setMinimumSize(new java.awt.Dimension(54, 140));
catTree.setOpaque(false);
catTree.addInteractionListener(new com.miginfocom.ashape.interaction.InteractionListener() {
    public void interactionOccured(com.miginfocom.ashape.interaction.InteractionEvent evt) {
        catTreeInteractionOccured(evt);
    }
    });
    westPanel.add(catTree);

    getContentPane().add(westPanel, java.awt.BorderLayout.WEST);

    southPanel.setBackground(new java.awt.Color(255, 255, 255));
    southPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 0, 0));
    getContentPane().add(southPanel, java.awt.BorderLayout.SOUTH);

    mainParentPanel.setBackground(new java.awt.Color(255, 255, 255));
    mainParentPanel.setPreferredSize(new java.awt.Dimension(7, 12));
    mainParentPanel.setLayout(new java.awt.CardLayout());

    dayPanel.setLayout(new java.awt.BorderLayout());

    dayDateArea.setActivityLayouts(new com.miginfocom.calendar.layout.ActivityLayout[] {
        new com.miginfocom.calendar.layout.TimeBoundsLayout(new com.miginfocom.util.gfx.geometry.numbers.AtFraction(-0.5f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(0.0f), new com.miginfocom.util.gfx.geometry.numbers.AtStart(-1.0f), new com.miginfocom.util.gfx.geometry.numbers.AtEnd(1.0f), -1, null, null, null, new String[] {"TimeBounds"}, null)});
dayDateArea.setActivityPaintContext("day");
dayDateArea.setNorthDateHeader(overviewNorthHeader);
dayDateArea.setPrimaryDimension(javax.swing.SwingConstants.VERTICAL);
dayDateArea.setPrimaryDimensionCellType(com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_MINUTE);
dayDateArea.setPrimaryDimensionCellTypeCount(30);
dayDateArea.setPrimaryDimensionLayout(dayLayout);
dayDateArea.setVisibleDateRangeString("20090301T000000000-20090307T235959999");
dayDateArea.setWestDateHeader(dayTimeHeader);
dayDateArea.setWrapBoundary(new Integer(com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_DAY));
dayDateArea.setCategoryShowRoot(true);
dayDateArea.setDesignTimeHelp(false);
dayDateArea.setHorizontalGridLinePaintEven(new java.awt.Color(204, 204, 204));
dayDateArea.setHorizontalGridLinePaintOdd(new java.awt.Color(229, 229, 229));
dayDateArea.setHorizontalGridLineShowFirst(true);
dayDateArea.setHorizontalGridLineShowLast(true);
dayDateArea.setLabelNowBackground(new java.awt.Color(255, 204, 0));
dayDateArea.setMouseOverActivitiesOntop(true);
dayDateArea.setSelectedActivitiesOntop(true);
dayDateArea.setSelectionBoundaryType(com.miginfocom.util.dates.DateRangeI.RANGE_TYPE_MINUTE);
dayDateArea.setSelectionType(com.miginfocom.calendar.datearea.DateArea.SELECTION_TYPE_NORMAL);
dayDateArea.setShowNoFitIcon(true);
dayDateArea.setVerticalGridLinePaintEven(new java.awt.Color(204, 204, 204));
dayDateArea.setVerticalGridLinePaintOdd(new java.awt.Color(204, 204, 204));
dayDateArea.setVerticalGridLineShowFirst(true);
dayDateArea.addDateChangeListener(new com.miginfocom.util.dates.DateChangeListener() {
    public void dateRangeChanged(com.miginfocom.util.dates.DateChangeEvent evt) {
        dayDateAreaDateRangeChanged(evt);
    }
    });
    dayPanel.add(dayDateArea, java.awt.BorderLayout.CENTER);

    mainParentPanel.add(dayPanel, "day");

    getContentPane().add(mainParentPanel, java.awt.BorderLayout.CENTER);

    paintPanelBean1.setBackgroundPaint(new com.miginfocom.util.gfx.ShapeGradientPaint(new java.awt.Color(150, 150, 150), new java.awt.Color(190, 190, 190), 90.0f, 1.0f, 0.5f, false));
    paintPanelBean1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 0, 0, new java.awt.Color(135, 135, 135)), javax.swing.BorderFactory.createMatteBorder(1, 0, 0, 0, new java.awt.Color(239, 239, 239))));
    paintPanelBean1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 12, 3));

    separatedButton.setText(" Show Separated Calendars ");
    separatedButton.setFocusPainted(false);
    separatedButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            separatedButtonActionPerformed(evt);
        }
    });
    paintPanelBean1.add(separatedButton);

    jPanel1.setOpaque(false);
    jPanel1.setPreferredSize(new java.awt.Dimension(575, 10));
    paintPanelBean1.add(jPanel1);

    refreshButton.setText("Refresh");
    refreshButton.setFocusPainted(false);
    refreshButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            refreshButtonActionPerformed(evt);
        }
    });
    paintPanelBean1.add(refreshButton);

    programButton.setText("Program");
    programButton.setFocusPainted(false);
    programButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            programButtonActionPerformed(evt);
        }
    });
    paintPanelBean1.add(programButton);

    getContentPane().add(paintPanelBean1, java.awt.BorderLayout.SOUTH);

    northPanel.setBackgroundPaint(new com.miginfocom.util.gfx.ShapeGradientPaint(new java.awt.Color(153, 153, 153), new java.awt.Color(204, 204, 204), 90.0f, 0.70000005f, 0.5f, false));
    northPanel.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(100, 100, 100)));
    northPanel.setMaximumSize(new java.awt.Dimension(1280, 800));
    northPanel.setPreferredSize(new java.awt.Dimension(814, 40));
    northPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 7, 7));

    connectButton.setText("Connect");
    connectButton.setFocusPainted(false);
    connectButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            connectButtonActionPerformed(evt);
        }
    });
    northPanel.add(connectButton);

    spacer4.setOpaque(false);
    spacer4.setPreferredSize(new java.awt.Dimension(400, 12));
    northPanel.add(spacer4);

    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/miginfocom/beandemo/Apple-logo-02.png"))); // NOI18N
    jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
    northPanel.add(jLabel1);

    spacer3.setOpaque(false);
    spacer3.setPreferredSize(new java.awt.Dimension(350, 12));
    northPanel.add(spacer3);

    getContentPane().add(northPanel, java.awt.BorderLayout.PAGE_START);

    pack();
    }// </editor-fold>//GEN-END:initComponents

	private void catTreeInteractionOccured(com.miginfocom.ashape.interaction.InteractionEvent evt)
	{//GEN-FIRST:event_calendarsTreeInteractionOccured
		if (CategoryTreeBean.CHECK_CLICKED.equals(evt.getCommand().getValue()))
			currentDateArea.getDateArea().recreateActivityViews();

		setSeparateCheckEnabledState();
		setHeaderCategoryIDs();
	}//GEN-LAST:event_calendarsTreeInteractionOccured

	private void activityMonthAShapeMouseInteracted(com.miginfocom.ashape.interaction.MouseInteractionEvent evt)//GEN-FIRST:event_activityMonthAShapeMouseInteracted
	{//GEN-HEADEREND:event_activityMonthAShapeMouseInteracted
		// Code to show a dialog when you click an activity in the month view

//		if (evt.getEventKey() == MouseKeyInteractor.MOUSE_CLICK) {
//			Component comp = evt.getOriginalEvent().getComponent();
//
//			if (comp == currentDateArea.getDateArea()) {
//				ActivityView view = (ActivityView) evt.getMouseKeyInteractor().getInteracted();
//				JOptionPane.showMessageDialog(comp, "You clicked: " + view.getModel().getSummary());
//			}
//		}
	}//GEN-LAST:event_activityMonthAShapeMouseInteracted


	private void separatedButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_separatedButtonActionPerformed
	{//GEN-HEADEREND:event_separatedButtonActionPerformed
		if (separatedButton.isSelected() && separatedButton.isEnabled()) {
			separatedButton.setForeground(Color.WHITE);
			dayDateArea.setCategoryHeader(dayCategoryHeader);
		} else {
			separatedButton.setForeground(Color.BLACK);
			dayDateArea.setCategoryHeader(null);
		}

		setHeaderCategoryIDs();
		currentDateArea.revalidate();
	}//GEN-LAST:event_separatedButtonActionPerformed

    private void dayDateAreaDateRangeChanged(com.miginfocom.util.dates.DateChangeEvent evt) {//GEN-FIRST:event_dayDateAreaDateRangeChanged
        // This is the code that creates an activity by dragging in the day/days date area.
        if (evt.getType() == DateChangeEvent.PRESSED) {

            if (newCreatedAct == null && evt.getNewRange().getMillisSpanned(false, false) > 45*60*1000
                    && getSelectedCategoryLabelIDs()!=-1) {
                newCreatedAct = new DefaultActivity(evt.getNewRange(), new Long(new Random().nextLong()));
                newCreatedAct.setSummary("ON");
                newCreatedAct.addCategoryID(getSelectedCategoryLabelIDs(), -1);
                ActivityDepository.getInstance(dayDateArea.getActivityDepositoryContext()).addBrokedActivity(newCreatedAct, this, TimeSpanListEvent.ADDED_CREATED);
            } else {
                try {

                    newCreatedAct.setBaseDateRange(evt.getNewRange());
                } catch (Exception ex) {}
            }
        } else if (evt.getType() == DateChangeEvent.SELECTED) {
            if (newCreatedAct != null) {
                newCreatedAct.getStates().setStates(GenericStates.SELECTED_BIT, true);
                newCreatedAct = null;
            }
        }
}//GEN-LAST:event_dayDateAreaDateRangeChanged

    private void programButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_programButtonActionPerformed
        // TODO add your handling code here:
        System.out.println("Program Pressed");
        System.out.println("Collecting Data");        
        collectData();
        System.out.println("Data Collected");
        System.out.println("Programming Plug 1");        
		sendByte((byte)0xBC);
        System.out.println("Sending Data...");        
        sendBytes(result1);
        try{
        	Thread.sleep(100);
        }catch(Exception e){
        	e.printStackTrace();
        }
        System.out.println("Programming Plug 2");        
        sendByte((byte)0xBD);
        System.out.println("Sending Data...");        
        sendBytes(result2); 
        try{
        	Thread.sleep(100);
        }catch(Exception e){
        	e.printStackTrace();
        }
        System.out.println("Programming Plug 3");
        sendByte((byte)0xBE);
        System.out.println("Sending Data...");
        sendBytes(result3);
        try{
        	Thread.sleep(100);
        }catch(Exception e){
        	e.printStackTrace();
        }
        System.out.println("Programming Plug 4");
        sendByte((byte)0xBF);
        System.out.println("Sending Data...");
        sendBytes(result4);
}//GEN-LAST:event_programButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        // TODO add your handling code here:
        System.out.println("Refreshed Pressed");
        ActivityDepository.getInstance(dayDateArea.getActivityDepositoryContext()).removeAllBrokedActivities();
        //collectData();
        //byte []b1 = {0x6a,0,0x6b,0x3b};
        //byte []b2 = {0x2c,0x1e,0x2f,0x1d};
        //byte []b3 = {new Integer(0xAC).byteValue(), new Integer(0x1E).byteValue(), new Integer(0xAE).byteValue(), new Integer(0x3B).byteValue(), new Integer(0x4E).byteValue(), new Integer(0x1E).byteValue(), new Integer(0x50).byteValue(), new Integer(0x3B).byteValue()};
        //byte []b4 = {new Integer(0xef).byteValue(),  new Integer(0x32).byteValue(), new Integer(0xf2).byteValue(),  new Integer(0x31).byteValue()};
        
        //GET PLUG 1
        try{
            byte startByte = 0x3c;//need to verify
            this.out.write(startByte);
        }catch(Exception e){
            e.printStackTrace();
        }
        int byteCnt = 0;
        byte []data = new byte[128]; //assuming 4 intervals 7 days max 4*28 = 112
        try{
        	for(byteCnt = 0; byteCnt<128;byteCnt++){
        		data[byteCnt] = new Integer(this.in.read()).byteValue();
        		if(data[byteCnt] == 0x7f)
        			break;
        	}
        /*
         while ((data[byteCnt] = new Integer((this.in.read())).byteValue()) > -1 ){
            //System.out.print(data[byteCnt]);
            
            if (data[byteCnt] == 0x7f){ //need to verify
                System.out.println("End of data received");
                break;
            }
            byteCnt++;
            
        }
        */
        }catch(IOException e){
            e.printStackTrace();
        }
        System.out.println("Received data for 1 plug");
        printb(data,true, byteCnt);
        setUpActivities(0,data,byteCnt);
        
        
        //GET PLUG 2
         try{
            byte startByte = 0x3d;//need to verify
            this.out.write(startByte);
        }catch(Exception e){
            e.printStackTrace();
        }
        
        byteCnt = 0;
        data = new byte[128]; //assuming 4 intervals 7 days max 4*28 = 112
        try{
        	for(byteCnt = 0; byteCnt<128;byteCnt++){
        		data[byteCnt] = new Integer(this.in.read()).byteValue();
        		if(data[byteCnt] == 0x7f)
        			break;
        	}
        	/*
         while ((data[byteCnt] = new Integer((this.in.read())).byteValue()) > -1 ){
            //System.out.print(data[byteCnt]);
            
            if (data[byteCnt] == 0x7f){ //need to verify
                System.out.println("End of data received");
                break;
            }
            byteCnt++;
        }*/
        }catch(IOException e){
            e.printStackTrace();
        } 
        System.out.println("Received data for 2 plug");
        printb(data,true,byteCnt);
       setUpActivities(1,data,byteCnt);
       
       
       //GET PLUG 3
        try{
            byte startByte = 0x3e;//need to verify
            this.out.write(startByte);
        }catch(Exception e){
            e.printStackTrace();
        }
        
        byteCnt = 0;
        data = new byte[128]; //assuming 4 intervals 7 days max 4*28 = 112
        try{
        	for(byteCnt = 0; byteCnt<128;byteCnt++){
        		data[byteCnt] = new Integer(this.in.read()).byteValue();
        		if(data[byteCnt] == 0x7f)
        			break;
        	}
        /*
         while ((data[byteCnt] = new Integer((this.in.read())).byteValue()) > -1 ){
            //System.out.print(data[byteCnt]);
            
            if (data[byteCnt] == 0x7f){ //need to verify
                System.out.println("End of data received");
                break;
            }
            byteCnt++;
        }
        */
        }catch(IOException e){
            e.printStackTrace();
        }
        System.out.println("Received data for 3 plug");
        printb(data,true,byteCnt);
        setUpActivities(2,data,byteCnt);
        
        
        //GET PLUG 4
        try{
            byte startByte = 0x3f;//need to verify
            this.out.write(startByte);
        }catch(Exception e){
            e.printStackTrace();
        }
        
        byteCnt = 0;
        data = new byte[128]; //assuming 4 intervals 7 days max 4*28 = 112
        try{
        	for(byteCnt = 0; byteCnt<128;byteCnt++){
        		data[byteCnt] = new Integer(this.in.read()).byteValue();
        		if(data[byteCnt] == 0x7f)
        			break;
        	}
        /*
         while ((data[byteCnt] = new Integer((this.in.read())).byteValue()) > -1 ){
            //System.out.print(data[byteCnt]);
            
            if (data[byteCnt] == 0x7f){ //need to verify
                System.out.println("End of data received");
                break;
            }
            byteCnt++;
        }
        */
        }catch(IOException e){
            e.printStackTrace();
        }
        System.out.println("Received data for 4 plug");
        printb(data,true,byteCnt);
        setUpActivities(3,data,byteCnt);
        
       
    }//GEN-LAST:event_refreshButtonActionPerformed

    



    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        // TODO add your handling code here:

        ArrayList ports = new ArrayList();
        java.util.Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() )
        {
            CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum.nextElement();
            ports.add(portIdentifier.getName());
        }
        
        String s = (String)JOptionPane.showInputDialog(paintPanelBean1, "Select Comm Port", "Connect", JOptionPane.QUESTION_MESSAGE, null, ports.toArray(), "ham");
        try
        {                        
			connect(s);
                        programButton.setEnabled(true);
                        refreshButton.setEnabled(true);
                        
                        
                        
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println( e.toString());
        }
        
    }//GEN-LAST:event_connectButtonActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[])
	{
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//			UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
		} catch (Exception ex) {}

        com.miginfocom.util.LicenseValidator.setLicenseKey("Cu=Demo;Co=Demo;Dm=true;Pd=C;V=6;Ex=1243116000000;SignCode=3F;Signature=302D02150090C9FB7A283B80C5BF8EB75A96AB9AF83CAA956902142F38214A34D1C952D65AF61590920219E49CD840");
		java.awt.EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				new AppFrame().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.miginfocom.beans.ActivityAShapeBean activityDayAShape;
    private com.miginfocom.beans.ActivityAShapeBean activityMonthAShape;
    private com.miginfocom.beans.CategoryTreeBean catTree;
    private javax.swing.JButton connectButton;
    private com.miginfocom.beans.NorthCategoryHeaderBean dayCategoryHeader;
    private com.miginfocom.beans.DateAreaBean dayDateArea;
    private com.miginfocom.beans.DateHeaderBean dayDateHeader;
    private com.miginfocom.beans.GridDimensionLayoutBean dayLayout;
    private javax.swing.JPanel dayPanel;
    private com.miginfocom.beans.DateHeaderBean dayTimeHeader;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel mainParentPanel;
    private com.miginfocom.beans.PaintPanelBean northPanel;
    private com.miginfocom.beans.DateHeaderBean overviewNorthHeader;
    private com.miginfocom.beans.GridDimensionLayoutBean overviewVerticalLayout;
    private com.miginfocom.beans.DateHeaderBean overviewWestHeader;
    private com.miginfocom.beans.PaintPanelBean paintPanelBean1;
    private javax.swing.JButton programButton;
    private javax.swing.JButton refreshButton;
    private javax.swing.JToggleButton separatedButton;
    private javax.swing.JPanel southPanel;
    private javax.swing.JPanel spacer2;
    private javax.swing.JPanel spacer3;
    private javax.swing.JPanel spacer4;
    private com.miginfocom.beans.ActivityAShapeBean topDayAShape;
    private com.miginfocom.beans.DateHeaderBean weekDateHeader;
    private com.miginfocom.beans.GridDimensionLayoutBean weekLayout;
    private javax.swing.JPanel westPanel;
    private com.miginfocom.beans.DateGroupConnectorBean yearConnector;
    // End of variables declaration//GEN-END:variables

	static class CatCheckedFilter implements Filter
	{
		public boolean accept(Object o)
		{
			if (o instanceof Categorizable) {  // Activities are Categorizable...
				Object[] catIDs = ((Categorizable) o).getCategoryIDs();
				if (catIDs != null) {
					for (int c = 0; c < catIDs.length; c++) {
						Category cat = CategoryDepository.getCategory(catIDs[c]);
						if (cat != null && MigUtil.isTrue(cat.getProperty(CategoryTreeBean.CHECK_SELECTED_KEY)) == false) {
							return false;
						}
					}
				}
			}
			return true;
		}

		public String getName()
		{
			return "CatCheckedFilter";
		}
	}

	/** Filters out or in whole day activites
	 */
	static class DayActsFilter implements Filter
	{
		boolean showMultiDays;

		public DayActsFilter(boolean showMultiDays)
		{
			this.showMultiDays = showMultiDays;
		}

		public boolean accept(Object o)
		{
			return showMultiDays ^ ((Activity) o).getDateRangeForReading().getHasTime();
		}

		public String getName()
		{
			return "DayActsFilter";
		}
	}

	/** Listens for inteactions with the activities
	 */
	private class ActivityInteractionListener implements InteractionListener
	{
		public void interactionOccured(InteractionEvent e)
		{
			final Object o = e.getInteractor().getInteracted();

			if (o instanceof ActivityView && e.getSourceEvent() instanceof MouseEvent) {
				final ActivityView actView = (ActivityView) o;
				final DefaultDateArea dateArea = (DefaultDateArea) actView.getContainer();

				JPopupMenu pop = new JPopupMenu();
				final Point p = ((MouseEvent) e.getSourceEvent()).getPoint();
				Object commandValue = e.getCommand().getValue();

				if (DefaultDateArea.AE_POPUP_TRIGGER.equals(commandValue)) {
                    pop.add("Delete").addActionListener(new ActionListener() {
                       public void actionPerformed(ActionEvent e)
                       {
                           Activity act = ((ActivityView) o).getModel();
                           ActivityDepository.getInstance(dayDateArea.getActivityDepositoryContext()).removeBrokedActivity(act);
                       }
                    });
					pop.show(actView.getContainer(), p.x, p.y);

				} else if (DefaultDateArea.AE_DOUBLE_CLICKED.equals(commandValue)) {
					Activity act = ((ActivityView) o).getModel();
					String summary = JOptionPane.showInputDialog(dateArea, "Please enter a summary", act.getSummary());
					if (summary != null)
						act.setSummary(summary);
				}
			}
		}
	}
    void collectData(){

        java.util.List <Activity> l = ActivityDepository.getInstance().getBrokedActivities();
        int count = ActivityDepository.getInstance().getBrokedActivityCount();
        int dataIndex = 0;
        Calendar [] events = new Calendar [count*2];
        int [] plID = new int[count*2];
        for(Activity a : l){
            events[dataIndex] = a.getBaseDateRange().getStart();
            dataIndex++;
            events[dataIndex] = a.getBaseDateRange().getEnd();
            dataIndex++;    
            int plugId = 0;
            Object plug = a.getCategoryIDs()[0];
            if (plug.equals((Plug1ID))) plugId = 0;
            if (plug.equals((Plug2ID))) plugId = 1;
            if (plug.equals((Plug3ID))) plugId = 2;
            if (plug.equals((Plug4ID))) plugId = 3;
            plID [dataIndex-2] = plugId;
            plID [dataIndex-1] = plugId;
            }
        byte []res1 = new byte[count*4];
        byte []res2 = new byte[count*4];
        byte []res3 = new byte[count*4];
        byte []res4 = new byte[count*4];
        short i1,i2,i3,i4;
        i1=i2=i3=i4=0;
        byte [] bb = new byte[count*4];
        int byteCount = 0;
        for (int i = 0; i< count*2; i++){
            int min = events[i].get(Calendar.MINUTE);
            int hour = events[i].get(Calendar.HOUR_OF_DAY);
            int day = events[i].get(Calendar.DAY_OF_WEEK);     
            System.out.println("day = "+day );
            hour <<= 8;
            min = min | hour;
            day <<= 13;
            min = min | day;
            //plID[i] <<= 14;
            //min = min |(plID[i]<<14);
            String ss = String.format("%x", min);
            System.out.print ("  "+ss);
            switch (plID[i]){
                case 0:
                    
                    res1[i1+1] = new Integer(min).byteValue();
                    min >>>=8;
                    res1[i1] = new Integer(min).byteValue();
                    i1+=2;
                    break;
                case 1:
                    res2[i2+1] = new Integer(min).byteValue();
                    min >>>=8;
                    res2[i2] = new Integer(min).byteValue();
                    i2+=2;
                    break;
                case 2:
                    res3[i3+1] = new Integer(min).byteValue();
                    min >>>=8;
                    res3[i3] = new Integer(min).byteValue();
                    i3+=2;
                    break;
                case 3:
                    res4[i4+1] = new Integer(min).byteValue();
                    min >>>=8;
                    res4[i4] = new Integer(min).byteValue();
                    i4+=2;
                    break;
                default:
                    break;
            }
        }
      
        result1 = new byte[i1];
        for (int i = 0; i<i1; i++){
            result1[i] = res1[i];
        }
       
        result2 = new byte[i2];
        for (int i = 0; i<i2; i++){
            result2[i] = res2[i];
        }
       
        result3 = new byte[i3];
        for (int i = 0; i<i3; i++){
            result3[i] = res3[i];
        }
        
        result4 = new byte[i4];
        for (int i = 0; i<i4; i++){
            result4[i] = res4[i];
        }

		System.out.println("Collect End Print: ");
        if (i1!=0) printb(result1,true);
        if (i2!=0) printb(result2,true);
        if (i3!=0) printb(result3,true);
        if (i4!=0) printb(result4,true);
       

           // String s = String.format("bytes are %x and %x", bb[byteCount-2], bb[byteCount-1]);
          //  System.out.println("s = "+ s);
          
       
         
    }
    
    boolean sendByte(byte b){
    	try{
    		this.out.write(b);    	    	
    	} catch ( IOException e){    	    	
    		e.printStackTrace();
    		return false;
    	}
    	return true;    
    }
    
    boolean sendBytes(byte [] b){
    	try{
    		printb(b,true);
        	for (byte byteToSend: b){
           	    System.out.print(byteToSend+" ");
                this.out.write(byteToSend);           
	        }
 	        System.out.println("Send Termination Byte"); 
 	        try{
 	        Thread.sleep(100);
 	        }
 	        catch(Exception e)
    		{
    		e.printStackTrace();
    		return false;
    		}
	        this.out.write(0x7F);
        	int ack;
        	System.out.println("Waiting for Ack");        	           
        	ack = this.in.read();
        	System.out.println(ack);
    	    if (ack == 0xFC){
        	    System.out.println("Ack received");
            	return true;
	        }
        
  		}
    	catch ( IOException e )
    	{
             e.printStackTrace();
             return false;
    	}

        return false;
  	}
  	
    void printb(byte [] b, boolean hex){
       System.out.println("");
        for (byte bb: b){
            if (hex){
                String s = String.format("  %x",bb);
                System.out.print(s);
            }else {
                System.out.print("  "+bb);
            }
        }
       System.out.println("");
    }
        void printb(byte [] b, boolean hex,int len){
       System.out.println("");
        for (int i =0; i<len; i++){
            if (hex){
                String s = String.format("  %x",b[i]);
                System.out.print(s);
            }else {
                System.out.print("  "+b[i]);
            }
        }
       System.out.println("");
    }
    void setUpActivities(int plugID, byte [] bb, int length){
        //byte [] bb = {40,  30,  41,  59,  106,  0,  108,  59, 75,  30,  77,  59,  44,  0,  46,  29,  -82,  30,  -80,  29,  -55,  30,  -54,  59};
       // byte [] bb = {40,  30,  41,  59};
        //int length = 24;
        //int length = 4;
       
        for (int i = 0; i<length; i+=2 ){
           
           int startDayOfWeek = (bb[i]>>5)&0x07;
          // String s = String.format("bytes are %x and %x", bb[i]>>5, bb[i]>>>5);
          // System.out.println("s = "+ s);
           int startHourOfDay= bb[i]&0x1F;
           int startMinuteOfDay = bb[i+1];           
           i+=2;
            int endDayOfWeek = (bb[i]>>5)&0x07;
            int endHourOfDay= bb[i]&0x1F;
            int endMinuteOfDay = bb[i+1];
            long  startMillis = new GregorianCalendar(2009, 2, endDayOfWeek, startHourOfDay, startMinuteOfDay).getTimeInMillis();
            long endMillis = new GregorianCalendar(2009, 2, endDayOfWeek, endHourOfDay, endMinuteOfDay).getTimeInMillis();
            ImmutableDateRange dr = new ImmutableDateRange(startMillis, endMillis, false, null, null);
            System.out.println("Times from "+startHourOfDay+":"+startMinuteOfDay + " to "+ endHourOfDay + ":"+ endMinuteOfDay+" of day "+ endDayOfWeek);
            //RecurrenceRule rr = new RecurrenceRule(Calendar.WEEK_OF_YEAR, 1);
            //rr.addByXXXRule(new ByXXXRuleData(Calendar.DAY_OF_WEEK, new int[] {startDayOfWeek}));
            Activity a = new DefaultActivity(dr,new Long(new Random().nextLong()));
            //a.setRecurrence((rr));
            a.setSummary("ON");
             a.setLayoutContext("FlexGrid");
            switch(plugID){
                case 0: 
                    a.addCategoryID(Plug1ID,0);
                    break;
                case 1:
                    a.addCategoryID(Plug2ID, 0);
                    break;
                case 2: 
                    a.addCategoryID(Plug3ID,0);
                    break;
                case 3:
                    a.addCategoryID(Plug4ID, 0);
                    break;   
              }      
            
             ActivityDepository.getInstance().addBrokedActivity(a, AppFrame.class, TimeSpanListEvent.ADDED_CREATED);            
            //  a.getStates().setStates(GenericStates.SELECTED_BIT, true);
            //configureSelectedActivityChanges("");
            //configureSelectedActivityChanges("top_");
                a = null;
            // currentDateArea.getDateArea().setActivitiesSupported(true);
            //currentDateArea.getDateArea().recreateActivityViews();
            //configureMyActivities();
           
          
            
        }
         //System.out.println("second COLLECT");
           //collectData();
        // newCreatedAct = new DefaultActivity(evt.getNewRange(), new Long(new Random().nextLong()));
          //      newCreatedAct.setSummary("ON");
          //      newCreatedAct.addCategoryID(getSelectedCategoryLabelIDs(), -1);
          //      ActivityDepository.getInstance(dayDateArea.getActivityDepositoryContext()).addBrokedActivity(newCreatedAct, this, TimeSpanListEvent.ADDED_CREATED);
      
       
        
    }
     
    
    void connect ( String portName) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {

            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.disableReceiveThreshold();
                serialPort.enableReceiveTimeout(3000);
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
				in = serialPort.getInputStream();
				out = serialPort.getOutputStream();
                this.serialPort = serialPort;
            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

   
    static void listPorts()
    {
        java.util.Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() )
        {
            CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );
        }
    }

    static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
            case CommPortIdentifier.PORT_I2C:
                return "I2C";
            case CommPortIdentifier.PORT_PARALLEL:
                return "Parallel";
            case CommPortIdentifier.PORT_RAW:
                return "Raw";
            case CommPortIdentifier.PORT_RS485:
                return "RS485";
            case CommPortIdentifier.PORT_SERIAL:
                return "Serial";
            default:
                return "unknown type";
        }
    }
}
